package com.linkedList;

import java.util.List;

class MyLinkedList {

    static class ListNode{
        int val;
        ListNode next;
        ListNode(){};
        ListNode(int val){ this.val = val;}
    }
    int size = 0;
    //虚拟头节点
    ListNode dummyHead;

    public MyLinkedList() {
        size = 0;
        dummyHead = new ListNode(-1);
    }

    public int get(int index) {
        if(index < 0 || index>=size) return -1;

        ListNode cur = dummyHead;
        while (index >= 0){
            cur = cur.next;
            index--;
        }
        return cur.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0,val);
    }

    public void addAtTail(int val) {
        addAtIndex(size,val);
    }

    public void addAtIndex(int index, int val) {
        if(index > size ) return;
        if(index < 0 ) index = 0;

        size++;
        ListNode newNode = new ListNode(val);
        ListNode cur = dummyHead;
        while (index >0){
            cur = cur.next;
            index--;
        }
        newNode.next = cur.next;
        cur.next = newNode;
    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= size) return;

        size--;
        ListNode pre = dummyHead;
        while (index >0){
            pre = pre.next;
            index--;
        }
        pre.next = pre.next.next;
    }
}



